package com.chenyue.cm.api.goods;


import cn.hutool.core.date.DateUtil;
import com.chenyue.cm.account.domain.JdAccount;
import com.chenyue.cm.account.domain.JdIntegralRecord;
import com.chenyue.cm.account.domain.JdIntegralSource;
import com.chenyue.cm.account.service.JdAccountService;
import com.chenyue.cm.account.vo.AccountSource;
import com.chenyue.cm.account.vo.IntegralSource;
import com.chenyue.cm.auth.Login;
import com.chenyue.cm.auth.LoginUser;
import com.chenyue.cm.base.aop.Log;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.Constants;
import com.chenyue.cm.common.constant.ErrorCode;
import com.chenyue.cm.common.vo.Page;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.user.domain.JdGoodsSku;
import com.chenyue.cm.user.domain.JdGoodsSpu;
import com.chenyue.cm.user.domain.JdOrderInfo;
import com.chenyue.cm.user.domain.vo.*;
import com.chenyue.cm.user.service.*;
import com.chenyue.cm.utils.DateUtils;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
import javax.annotation.Resource;
import java.util.List;


@RestController
@RequestMapping("/api/order")
@Api(value = "订单相关", tags = "订单相关")
public class ApiOrderController {

    @Resource
    private JdAppUserService jdAppUserService;
    @Resource
    private JdOrderInfoService jdOrderInfoService;
    @Resource
    private JdOrderLogService jdOrderLogService;
    @Resource
    private JdGoodsSpuService spuService;
    @Resource
    private JdGoodsSkuService skuService;
    @Resource
    private JdAccountService jdAccountService;


    /**
     * 生成普通商品订单
     * 【O1002】
     *
     * @param request
     * @param response
     * @return
     */
    @Login
    @PostMapping("/saveGoodsOrder")
    @ApiOperation(value = "【O1002】生成订单", notes = "生成订单")
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "详细地址", name = "addressInfo", dataType = "string", required = true),
            @ApiImplicitParam(value = "用户地址ID", name = "addressId", dataType = "string", required = true),
            @ApiImplicitParam(value = "商品ID", name = "spuId", dataType = "string", required = true),
            @ApiImplicitParam(value = "商品名称", name = "spuInfo", dataType = "string", required = true),
            @ApiImplicitParam(value = "商品规格Id", name = "skuId", dataType = "string", required = true),
            @ApiImplicitParam(value = "商品规格", name = "skuInfo", dataType = "string", required = true),
            @ApiImplicitParam(value = "商品数量", name = "number", dataType = "Integer", required = true),
            @ApiImplicitParam(value = "商品单价", name = "money", dataType = "Integer", required = true),
            @ApiImplicitParam(value = "备注", name = "remark", dataType = "string")
    })
    @Log(value = "生成订单")
    public Success saveGoodsOrder(@ApiIgnore @LoginUser JdAppUser user,
                                  //地址参数: 地址address--- 省IDor省Name、市IDor市Name、县IDor县Name、
                                  //商品参数：商品ID 商品信息 规格ID 规格信息
                                  //订单参数：商品数量number 单价monery
                                  //remark
                                  String addressInfo,String addressId,String spuId,String spuInfo,
                                  String skuId,String skuInfo,Integer number,Integer money,String remark) {

        if (addressInfo == null) {
            return Success.error("请选择收货地址");
        }
        if (spuId == null && spuInfo == null) {
            return Success.error("请选择商品");
        }
        if (skuId == null && skuInfo == null) {
            return Success.error("请选择商品规格");
        }
        JdAccount account = jdAccountService.getIntergnal(Integer.valueOf(user.getId()));
        Integer integral = account.getIntegral();
        //核算支付金额
        Integer decimal = 0;
        //校验余额
        if (integral == 0 || integral < decimal) {
            return Success.fail(ErrorCode.BALANCE);
        }
        GoodsJSVo goodsJSVo = new GoodsJSVo();
        goodsJSVo.setUserId(user.getId().toString());
        goodsJSVo.setAddressDetail(addressInfo);
        goodsJSVo.setIntegral(money);
        goodsJSVo.setNumber(number);
        goodsJSVo.setRemark(remark);
        goodsJSVo.setSkuId(skuId);
        goodsJSVo.setSpuId(spuId);
        goodsJSVo.setTotalPrice(number*money);
        goodsJSVo.setAddressId(addressId);
        goodsJSVo.setSkuInfo(skuInfo);
        goodsJSVo.setSpuInfo(spuInfo);
        JdOrderInfo orderInfo = jdOrderInfoService.saveGoodsOrder(goodsJSVo);
        if (orderInfo == null){
            return Success.error(ErrorCode.INSUFFICIENT.getMsg());
        }
        //对应商品的兑换量+1
        JdGoodsSpu goodsSpu = spuService.getById(spuId);
        goodsSpu.setExchange(goodsSpu.getExchange()+1);
        spuService.updateById(goodsSpu);
        //库存-1
        JdGoodsSku goodsSku = skuService.getById(skuId);
        goodsSku.setSkuStock(Math.max(goodsSku.getSkuStock() - 1,0));
        goodsSku.setSkuSales(goodsSku.getSkuSales()+1);
        skuService.updateById(goodsSku);
        //扣积分
        jdAccountService.integralCostume(Integer.valueOf(user.getId()),orderInfo.getOrderMoney(), IntegralSource.SHOPPING,orderInfo.getId());
        orderInfo.setOrderStatus(Constants.ORDER_STATUS_1);

        //更新订单状态
        orderInfo.setPayTime(DateUtils.getTimeNow());
        boolean save = jdOrderInfoService.updateById(orderInfo);
        return save ? Success.success() : Success.error(ErrorCode.INSERT_ERROR.getMsg());
    }


    /**
     * 获取个人首页订单信息
     * 【O1003】
     *
     * @param request
     * @param response
     * @return
     */
    @Login
    @PostMapping("/getMemberOrderList")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "类型（0-全部，1-待发货，2-已发货,3-已完成）", name = "orderType", dataType = "Integer", required = true),
            @ApiImplicitParam(value = "当前页", name = "page", dataType = "int", required = true),
            @ApiImplicitParam(value = "条数", name = "rows", dataType = "int", required = true),
    })
    @ApiOperation(value = "【O1003】获取个人订单信息", notes = "获取个人订单信息")
    @ApiOperationSupport(order = 3)
    @Log(value = "获取个人订单信息")
    public Success<Page<List<OrderResultListVo>>> getMemberOrderList(@ApiIgnore @LoginUser JdAppUser user
        ,Integer page,Integer rows,Integer orderType)
    {
        if(user == null){
            return Success.error();
        }
        Page<List<OrderResultListVo>> getMemberOrderList = jdOrderInfoService.getMemberOrderList(user.getId().toString(), page, rows, orderType);
        return Success.success(getMemberOrderList);
    }


    /**
     * 根据 获取订单详情信息
     * 【O1004】
     *
     * @param request
     * @param response
     * @return
     */
    @Login
    @PostMapping("/getGoodsOrderDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "订单id", name = "orderId", dataType = "string"),
//            @ApiImplicitParam(value = "商品id（售后）", name = "goodsId", dataType = "string"),
//            @ApiImplicitParam(value = "规格id（售后）", name = "skuId", dataType = "string"),
//            @ApiImplicitParam(value = "flag(1-列表，2-售后，3-评价)", name = "flag", dataType = "string"),
    })
    @ApiOperation(value = "【O1004】根据 获取订单详情信息", notes = "根据 获取订单详情信息")
    @ApiOperationSupport(order = 4)
    @Log(value = "根据订单id获取订单详情信息")
    public Success<OrderDetailVo> getGoodsOrderDetail(@ApiIgnore @LoginUser JdAppUser user,
            String orderId) {
        if(user == null){
            return Success.error();
        }
        OrderDetailVo orderDetailVo = jdOrderInfoService.getOrderDetail(user,orderId);
        return Success.success(orderDetailVo);
    }


    /**
     * 取消订单
     * 【O1009】
     *
     * @param request
     * @param response
     * @return
     */
    @Login
    @PostMapping("/cancellationOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "订单id", name = "orderId", dataType = "string"),
    })
    @ApiOperation(value = "【O1005】根据 取消订单", notes = "根据 取消订单")
    @ApiOperationSupport(order = 5)
    @Log(value = "根据订单id取消订单")
    public Success cancellationOrder(@ApiIgnore @LoginUser JdAppUser user,
                                     String orderId) {
        if(user == null) {
            return Success.error();
        }
        JdOrderInfo orderInfo = jdOrderInfoService.getById(orderId);
        //对应商品的兑换量-1
        JdGoodsSpu goodsSpu = spuService.getById(orderInfo.getSpuId());
        goodsSpu.setExchange(Math.max(goodsSpu.getExchange() - 1,0));
        spuService.updateById(goodsSpu);
        //对应规格商品库存+1 兑换量-1
        JdGoodsSku goodsSku = skuService.getById(orderInfo.getSkuId());
        goodsSku.setSkuStock(goodsSku.getSkuStock()+1);
        goodsSku.setSkuSales(Math.max(goodsSku.getSkuSales()-1,0));
        skuService.updateById(goodsSku);
        //退款
        jdAccountService.integralRecharge(user.getId(),orderInfo.getOrderMoney(), IntegralSource.REFUND,orderId,"用户取消订单");
        return this.jdOrderInfoService.cancellationOrder(user.getId().toString(), orderId);
    }


    //删除订单
    /**
     * 删除订单
     * 【O1009】
     *
     * @param request
     * @param response
     * @return
     */
    @Login
    @PostMapping("/deleteOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "订单id", name = "orderId", dataType = "string"),
    })
    @ApiOperation(value = "【O1006】根据订单ID删除订单", notes = "根据 根据订单ID删除订单")
    @ApiOperationSupport(order = 6)
    @Log(value = "根据订单id删除订单")
    public Success deleteOrder(@ApiIgnore @LoginUser JdAppUser user,
                                     String orderId) {
        if(user == null) {
            return Success.error();
        }
        boolean b = jdOrderInfoService.removeById(orderId);
        return b?Success.success():Success.error();
    }




    //确认收货
    @Login
    @PostMapping("/receiveOrder")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "订单id", name = "orderId", dataType = "string"),
    })
    @ApiOperation(value = "【O1007】根据 确认收货", notes = "根据 确认收货")
    @ApiOperationSupport(order = 7)
    @Log(value = "根据订单id确认收货")
    public Success receiveOrder(@ApiIgnore @LoginUser JdAppUser user,
                               String orderId) {
        if(user == null) {
            return Success.error();
        }
        JdOrderInfo orderInfo = jdOrderInfoService.getById(orderId);
        if (orderInfo.getOrderStatus() == 2) {
            orderInfo.setCompleteTime(DateUtil.date().toStringDefaultTimeZone());
            orderInfo.setOrderStatus(3);
            boolean b = jdOrderInfoService.updateById(orderInfo);
            return b?Success.success():Success.error();
        }else {
            return Success.error(500,"订单还未发货");
        }
    }


}
